<?php
/**
 * 微信公众号关注回调
 * User: cxm
 * Date: 2020/9/27
 * Time: 14:19
 */
namespace App\Http\Controllers\Weixin;
use App\Http\Controllers\Controller;
use App\Models\UserWeixin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Text;
use EasyWeChat\Kernel\Messages\Message;
use Session;

class CallbackController extends Controller {
    /**
     * 微信公众号
     * @var object
     */
    protected $wechat;

    /**
     * 构造方法
     * CallbackController constructor.
     */
    public function __construct()
    {
        $config = config('wechat.official_account.default');
        $config['oauth']['callback']  = url('weixin/oauthCallback');
        $this->wechat = Factory::officialAccount($config);
    }

    /**
     * 用户授权
     * URL POST:/weixin/userScopes
     * @return mixed
     */
    public function userScopes(){
        $response = $this->wechat->oauth->scopes(['snsapi_userinfo'])->redirect();
        return $response;
    }

    /**
     * 授权回调
     * URl ANY:/weixin/oauthCallback
     * @return mixed
     * @throws
     */
    public function oauthCallback(){
        $code = \request()->get('code');
        $user = $this->wechat->oauth->user();
        $url = env('APP_URL');
        $unionid = $user['original']['unionid'];
        $user_weixin = UserWeixin::where('unionid',$unionid)->first();
        if (!$user_weixin) {
            $user_weixin = new UserWeixin();
            $user_weixin->openid_mp  = $user['original']['openid'];
            $user_weixin->unionid    = $unionid;
            $user_weixin->nickname   = $user['original']['nickname'];
            $user_weixin->sex        = $user['original']['sex'];
            $user_weixin->city       = $user['original']['city'];
            $user_weixin->province   = $user['original']['province'];
            $user_weixin->country    = $user['original']['country'];
            $user_weixin->language   = $user['original']['language'];
            $user_weixin->headimgurl = $user['original']['headimgurl'];
            $result = $user_weixin->save();
        }else{
            $user_weixin->openid_mp  = $user['original']['openid'];
            $result = $user_weixin->save();
        }
        if ($result === false) {
            return redirect($url.'/h5/#/success?error=微信信息保存失败');
        }
        return redirect($url.'/h5/#/success?success=ok&openid='.$user['original']['openid']);
//        return redirect('https://mp.weixin.qq.com/s/akmxpLls7DIO_drTctlhZw');
    }

    /**
     * 获取用户信息
     * URL ANY:weixin/userinfo
     * @param Request $request
     * @param string openid
     * @return mixed
     * @throws
     */
    public function getUserInfo(Request $request){
        $params = $request->only(['openid']);
        if (!array_key_exists('openid',$params) || empty($params['openid'])) {
            return $this->error('缺少openid');
        }
        $openId =$params['openid'];
        $user = $this->wechat->user->get($openId);
        //dd($user);
        if (!$user) {
            return $this->error('没有用户信息');
        }
        $subscribe = $user['subscribe'];
        if ($subscribe == 1) { // 已关注
            UserWeixin::where('openid_mp',$params['openid'])->update(['is_follow'=>1]);
        }
        return $this->success('查询成功',$user);
    }

    /**
     * 验证开发者 / 接收用户发送消息
     * URL GET:/callback
     * @param Request $request
     * @return mixed
     * @throws
     */
    public function weixinFollow()
    {
        $app = Factory::officialAccount(config('wechat.official_account.default'));
        // 上传图片
//        $result = $app->material->uploadImage(public_path()."/image/code.jpg");
//        Log::info("图片信息：".json_encode($result));
        $app->server->push(function($message){
             Log::info("消息：".json_encode($message));
             // $message['FromUserName'] // 用户的 openid
             // $message['MsgType'] // 消息类型：event, text....
             switch ($message['MsgType']) {
                 case 'event': // 关注公众号时
                     if ($message['Event']=='subscribe') {
                         // 改变用户的关注状态
                         $openid = $message['FromUserName'];
                         $user_weixin = UserWeixin::where('openid_mp', $openid)->first();
                         if ($user_weixin && $user_weixin->is_follow == 2) {
                             UserWeixin::where('openid_mp', $openid)->update(['is_follow' => 1]);
                         }
//                         $this->sendText($message['FromUserName']);
                         // 发送小程序进入图片
//                         $mediaId = 'd74CHqw5b4QDoLg37hfuj9P0iQ3TZ61hW4heXe2vHXc';
//                         $image = new Image($mediaId);
//                         return $image;
                     }
                     break;
                 case 'text':
//                     $text = new Text('识别二维码进入小程序。');
//                     return $text;
                     break;
             }
        });
        return $app->server->serve();
    }

    /**
     * 发送文本(用客户发送消息)
     * @param $openId
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function sendText($openId){
        $app = Factory::officialAccount(config('wechat.official_account.default'));
        $message = new Text('识别二维码进入小程序');
        $result = $app->customer_service->message($message)->to($openId)->send();
        return $result;
    }

    /**
     * 发送菜单
     * URL POST:/weixin/addMenu
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function addMenu(){
        $app = Factory::officialAccount(config('wechat.official_account.default'));
        $buttons = [
            [
                "type" => "click",
                "name" => "今日歌曲",
                "key"  => "V1001_TODAY_MUSIC"
            ],
            [
                "name"       => "菜单",
                "sub_button" => [
                    [
                        "type" => "view",
                        "name" => "搜索",
                        "url"  => "http://www.soso.com/"
                    ],
                    [
                        "type" => "view",
                        "name" => "视频",
                        "url"  => "http://v.qq.com/"
                    ],
                    [
                        "type" => "click",
                        "name" => "赞一下我们",
                        "key" => "V1001_GOOD"
                    ],
                ],
            ],
        ];
        return $app->menu->create($buttons);
    }
}